<style scoped lang="less">
.area-tree {
  height: 100%;
  height: calc(100% - 38px);
  overflow: auto;
}
</style>
<template>
  <div class="area-tree" v-loading="loading">
    <el-tree
      :data="data"
      node-key="id"
      :load="loadNode"
      lazy
      :props="defaultProps"
      @node-click="handleNodeClick"
      unselectable="on"
      :expand-on-click-node="false"
      :default-expanded-keys="defaultExpandedKeys"
      :indent="36"
      @node-contextmenu="showContextMenu"
      ref="areaTree"
    >
      <div
        class="tree-node"
        :class="{ active: activeNodeId == node.id }"
        slot-scope="{ node, data }"
      >{{ data.name }}</div>
    </el-tree>
    <ul class="context-menu" v-if="menuVisible" :style="{ left: menuX + 'px', top: menuY + 'px' }">
      <li
        v-for="(item, index) in menuList"
        :key="index"
        @click="menuHandler(item.handler)"
      >{{ item.name }}</li>
    </ul>
    <!-- 添加/编辑 start -->
    <el-dialog
      :title="newModalTitle"
      :visible.sync="newModalVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
    >
      <el-form ref="newForm" :model="newForm" label-width="120px">
        <el-form-item label="父级行政区划：" v-if="activeParentName">
          {{
          activeParentName
          }}
        </el-form-item>
        <el-form-item
          label="名称："
          prop="name"
          :rules="[
            { required: true, message: '请输入名称', trigger: 'change' },
          ]"
        >
          <el-input placeholder="请输入" type="text" v-model.trim="newForm.name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="cancel" @click="newModalVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="adding"
          @click="submitAction"
          :disabled="!$store.getters.hasEditPermission"
        >确定</el-button>
      </div>
    </el-dialog>
    <!-- 添加/编辑 end -->
  </div>
  <!-- render-content="renderContent" -->
</template>
<script>
import { mapState } from "vuex";
export default {
  name: "iotBlk",
  props: {
    title: {
      type: String,
      default: ""
    },
    moreType: {
      type: Number,
      default: 0
    },
    size: {
      type: String,
      default: "small"
    },
    isEditable: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ""
    },
    lastRegion: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapState(["scale"]),
    ...mapState(["siteInfos"]),
    defaultExpandedKeys() {
      // if (this.data.length > 0) {
      // 	let ids = [];
      // 	let provs = this.data[0].regions;
      // 	let citys = [];
      // 	provs.forEach((item, index) => {
      // 		citys = [...citys, ...item.regions];
      // 	});
      // 	ids = citys.map((item) => item.id);
      // 	return ids;
      // }
      return [];
    },
    activeParentName() {
      if (!this.activeData) return "";
      let allname = this.activeData.allname.split(",");
      // if (allname.length == 1) return "中国"
      return allname[allname.length - 1];
    }
  },
  watch: {},
  data() {
    return {
      loading: false,
      data: [],
      defaultProps: {
        children: "regions",
        label: "name",
        isLeaf: "leaf"
      },
      activeNodeId: "",

      activeData: null,
      menuList: [],
      menuVisible: false,
      menuX: 0,
      menuY: 0,
      newModalTitle: "新建",
      newModalVisible: false,
      newForm: {},
      adding: false,
      treeList: null
    };
  },
  created() {
    // this.getRegions()
  },
  mounted() {
    document.addEventListener("click", this.clickDom, false);
  },
  beforeDestroy() {
    document.removeEventListener("click", this.clickDom, false);
  },
  methods: {
    loadNode(node, resolve) {
      let pid = 0;
      if (node.level == 0 && this.type == "all") {
        resolve([{ name: "中国", id: 0, allname: "中国" }]);
      } else {
        let id = this.type == "all" ? null : this.siteInfos.reginId;
        pid = node.data.id || id;
        this.getRegions(pid || "0", data => {
          const temp = data.map(item => {
            item.leaf = node.level == 5;
            return item;
          });
          resolve(temp);
        });
      }
    },
    getRegions(pid, cbk) {
      this.loading = true;
      this.$get("/business/business/regionLists", { pid }).then(
        res => {
          this.loading = false;
          if (!this.treeList) {
            this.treeList = res.data;
          }
          cbk && cbk(res.data);
        },
        err => {
          this.loading = false;
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    getRegion() {
      this.loading = true;
      this.$get("/business/business/regionList").then(
        res => {
          this.loading = false;
          res.data.name = "中国";
          this.data = [res.data];
        },
        err => {
          this.loading = false;
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    getAllAreaName(node, names) {
      names.push(node.data.name);
      if (node.parent && node.data.pid != 0) {
        this.getAllAreaName(node.parent, names);
      }
    },
    handleNodeClick(data, node, n) {
      this.activeNodeId = node.id;
      let areaNames = [];
      this.getAllAreaName(node, areaNames);
      areaNames = areaNames.reverse();
      this.$emit("nodeClick", data, node.level, areaNames);
      this.hideMenu();
    },

    showContextMenu(event, data, node, el) {
      if (!this.isEditable) return;
      let menuList = [];
      if (this.$store.getters.hasEditPermission) {
        if (node.level < 6 && this.hasPermission("006002001")) {
          menuList.push({
            name: "新建下级",
            handler: "new"
          });
        }
        if (this.hasPermission("006002002")) {
          menuList.push({
            name: "编辑",
            handler: "edit"
          });
        }
        if (this.hasPermission("006002003")) {
          menuList.push({
            name: "删除",
            handler: "delete"
          });
        }
      }
      this.menuList = menuList;
      this.activeNode = node;
      this.activeData = node.data;
      this.menuVisible = true;
      this.menuX = event.clientX;
      this.menuY = event.clientY;
    },
    menuHandler(type) {
      this.menuVisible = false;
      if (type == "new") {
        this.newRegion();
      } else if (type == "edit") {
        this.editRegion();
      } else if (type == "delete") {
        this.deleteRegion();
      }
    },
    hideMenu() {
      this.menuVisible = false;
      // this.activeNode = null
    },
    clickDom() {
      this.hideMenu();
    },
    newRegion() {
      this.newModalTitle = "新建行政区划";
      this.newForm = {};
      this.newForm.pid = this.activeData.id;
      this.newModalVisible = true;
      if (this.$refs["newForm"]) {
        this.$refs["newForm"].resetFields();
      }
    },

    editRegion() {
      this.newModalTitle = "编辑行政区划";
      this.newForm = {
        id: this.activeData.id,
        name: this.activeData.name
      };
      this.newModalVisible = true;
    },
    deleteRegion() {
      this.showConfirm("确定删除该行政区划吗？", () => {
        this.deleting = true;
        this.$post("/business/business/regionDel", {
          id: this.activeData.id
        }).then(
          res => {
            this.deleting = false;
            this.$message.success("删除成功");
            this.$refs.areaTree.remove(this.activeNode);
            // this.removeNode(this.activeNode, this.activeData)
          },
          err => {
            this.deleting = false;
            this.$message.error(err.msg);
          }
        );
      });
    },
    removeNode(node, data) {
      const parent = node.parent;
      const children = parent.data.regions || parent.data;
      const index = children.findIndex(d => d.id === data.id);
      children.splice(index, 1);
    },
    submitAction() {
      this.$refs["newForm"].validate(valid => {
        if (valid) {
          this.adding = true;
          let params = Object.assign({}, this.newForm);
          let url = "";
          let isEdit = !!this.newForm.id;
          if (this.newForm.id) {
            url = "/business/business/regionUpdate";
          } else {
            url = "/business/business/regionAdd";
          }
          this.$post(url, params).then(
            res => {
              this.adding = false;
              this.$message.success("保存成功");
              this.newModalVisible = false;
              this.getRegion();
              if (isEdit) {
                this.activeData.name = this.newForm.name;
              } else {
                if (!this.activeData.regions) {
                  this.$set(this.activeData, "regions", []);
                }
                this.activeData.regions.push(res.data);
              }
            },
            error => {
              this.adding = false;
              this.$message.error(error.msg);
            }
          );
        } else {
          return false;
        }
      });
    }
  }
};
</script>
